<?php
require_once __DIR__ . '/vendor/autoload.php';
include_once __DIR__ ."/callback/WXBizMsgCrypt.php";
include_once __DIR__ ."/callback/xmlparse.php";

use Workerman\Protocols\Ws;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;

$logStr = "";
$corpid = "ww5be4fc8e2add2759";
$secretid = "qBoEE3nZtFd5hLlBWUfUscnYDwU2aK3jDrxrlzpJduU";
$accessToken = "";
$lastCursor = "";

/** 
//拉取客服消息
$url = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=$accessToken&cursor=''&token=$accessToken&open_kfid=kfcaf1dab2114d3b3a7";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo "$response ++\n";*/

$updateToken = function()
{
	global $corpid;
	global $secretid;

	$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid&corpsecret=$secretid";
	echo "++++++++++++++++!!++++++++++++++++\n";
	echo "theurl=$url \n";
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);
	
	echo "$response --\n";
	$rsp = json_decode($response);
	
	global $accessToken;
	$accessToken = $rsp->access_token;
	echo "token=$accessToken \n";
};

//获取access_token
$updateToken();

$httpGet = function($url)
{
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	curl_close($ch);
	return $response;
};
$httpPost = function($url, $data)
{
	// POST 请求的目标 URL
	
	// POST 请求的数据
	/**$data = array(
		'param1' => 'value1',
		'param2' => 'value2'
	);*/
	
	// 初始化 cURL
	$ch = curl_init();
	//$json = http_build_query($data);
	$json = json_encode($data);
	//echo "\n--------------json=\n";
	//echo $json;
	//echo "\n------------json-------------\n";
	
	// 设置 cURL 选项
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$headers = array(
		'accept: application/json',
		'Content-type: application/json'
	);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	
	// 执行 POST 请求
	$response = curl_exec($ch);
	
	// 关闭 cURL 资源
	curl_close($ch);
	
	// 输出响应结果
	return $response;
};

// 所有的打印输出全部保存在/tmp/stdout.log文件中
Worker::$stdoutFile = __DIR__ ."/stdout.log";
// 创建一个Worker监听2345端口，使用http协议通讯
$http_worker = new Worker("http://0.0.0.0:2346");

// 启动4个进程对外提供服务
$http_worker->count = 1;

// 接收到浏览器发送的数据时回复hello world给浏览器
$http_worker->onMessage = function(TcpConnection $connection, Request $request)
{
    // 向浏览器发送hello world
	//$connection->send('hello world');

	//-----------------------验证消息-----------------------//
	// 假设企业号在公众平台上设置的参数如下
	$encodingAesKey = "zndOCwNj2RsP5eZWIrjVzyJVMdknNvacUNR82F1Xb70";
	$token = "lHwn170U";
	$receiveid = "ww5be4fc8e2add2759";
	$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);

	// get the paramters
	$sVerifyMsgSig = $request->get('msg_signature');
	$sVerifyTimeStamp = $request->get('timestamp');
	$sVerifyNonce = $request->get('nonce');
	$sReqData = $request->rawBody();

	$sEchoStr = "";

	// call verify function
	$errCode = $wxcpt->DecryptMsg($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sReqData, $sEchoStr);
	if ($errCode == 0) {
		//echo $sEchoStr . "\n";
		$connection->send($sEchoStr);

	} else {
		print("ERR: " . $errCode . "\n\n");
	}
	//echo $sEchoStr;
	//echo "\n---------------------------------\n";

	$method = $request->method();
	echo "method=$method\n";
	//echo $request->uri();
	//return;

	if($errCode != 0){//} ($method == "get"){//$_SERVER['REQUEST_METHOD'] === 'GET') {
		echo "\n|---------------消息验证错误！------------------|\n";
		return;
		//之前的回调配置处理
		$msg_signature = $request->get('msg_signature');
		$timestamp = $request->get('timestamp');
		$nonce = $request->get('nonce');
		$echostr = $request->get('echostr');
	
		// 假设企业号在公众平台上设置的参数如下
		$encodingAesKey = "zndOCwNj2RsP5eZWIrjVzyJVMdknNvacUNR82F1Xb70";
		$token = "lHwn170U";
		$receiveid = "ww5be4fc8e2add2759";
		$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);
	
		// get the paramters
		$sVerifyMsgSig = $request->get('msg_signature');
		$sVerifyTimeStamp = $request->get('timestamp');
		$sVerifyNonce = $request->get('nonce');
		$sVerifyEchoStr = $request->get('echostr');
	
		$sEchoStr = "";
	
		// call verify function
		$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
		if ($errCode == 0) {
			echo $sEchoStr . "\n";
		} else {
			print("ERR: " . $errCode . "\n\n");
		}
	}
	else{//验证成功

		// 假设企业号在公众平台上设置的参数如下
		$encodingAesKey = "zndOCwNj2RsP5eZWIrjVzyJVMdknNvacUNR82F1Xb70";
		$token = "lHwn170U";
		$receiveid = "ww5be4fc8e2add2759";
		$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);

		$msg_signature = $request->get("msg_signature");
		$timestamp = $request->get("timestamp");
		$nonce = $request->get("nonce");
		// post请求的密文数据
		$sReqData = $request->rawBody();
		$sMsg = "";  // 解析之后的明文
		//echo "msg_signature=$msg_signature \n";
		//echo "timestamp=$timestamp \n";
		//echo "nonce=$nonce \n";

		$errCode = $wxcpt->DecryptMsg($msg_signature, $timestamp, $nonce, $sReqData, $sMsg);
		if ($errCode == 0) {
			// 解密成功，sMsg即为xml格式的明文
			//var_dump("sMsg=$sMsg\n");
			echo "消息验证成功--------------------------------->\n";
			
			$xml = new DOMDocument();
			$xml->loadXML($sMsg);
			$array_e = $xml->getElementsByTagName('Token');
			$Token = $array_e->item(0)->nodeValue;
			$array_e = $xml->getElementsByTagName('OpenKfId');
			$OpenKfId = $array_e->item(0)->nodeValue;

			//var_dump($encrypt);
			//请求消息内容
			//echo "\n---------------------------------";
			global $httpGet;
			global $httpPost;
			global $accessToken;
			global $lastCursor;
			$url1 = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=$accessToken";
			$url1 = $url1."&open_kfid=$OpenKfId";
			$url1 = $url1."&token=$token";
			$url1 = $url1."&cursor=$lastCursor";

			echo "msg OpenKfId=".$OpenKfId."\n";
			
			$post_data = array(
				"access_token" => $accessToken,
				"open_kfid" => $OpenKfId,
				"token" => $Token,
				"cursor" => $lastCursor,
				"voice_format" => 0,
				"limit" => 0,
			);
			$response = $httpGet($url1, $post_data);
			$rspArr = json_decode($response);
			if($rspArr->errcode != 0){
				echo "\n请求消息失败！OpenKfId=$OpenKfId,errcode=$rspArr->errcode";

				global $updateToken;
				$updateToken();
				return;
			}
			else{

			}
			$lastCursor = $rspArr->next_cursor;
			$msgList = $rspArr->msg_list;
			//echo "\n---------------------------------";
			$length = count($msgList);
			//var_dump($msgList);

			echo "msg length=".$length."\n";

			if($length <= 0){
				$endMsg = array(
					"text" => array(
						"content" => "hello",
					)
				);
			}
			else{
				$endMsg = $msgList[$length - 1];
			}
			//历史记录，弄个3条发给ai语言模型
			/**$startIdx = $length - 4;
			$endIdx = $length - 1;
			if($startIdx < 0){
				$startIdx = 0;
			}
			$history = array();
			for($i = $startIdx; $i < $endIdx; $i++){
				array_push($history, array(
					"role" => "user",
					"content" => $msgList[$i]->text->content
				));
			}
			echo "\n----------------history-----------------\n";
			var_dump($history);**/
			$history = array(
				array(
					"role" => "user",
					"content" => "我们来玩成语接龙，我先来，生龙活虎"
				),
				array(
					"role" => "assistant",
					"content" => "虎头虎脑"
				));
			//echo "\n----------------history2-----------------\n";
			//var_dump($history);

			//msgid,open_kfid,external_userid,send_time,origin,msgtype,text{"content":"xxx"}
			echo "userid=$endMsg->external_userid\n";
			echo "用户:".$endMsg->text->content;
			//echo "$lastCursor\n";
			//var_dump($rspArr);

			//var_dump($response);

			//向AI请求消息,http
			/**$url1 = "https://8919j8p607.vicp.fun/chat/completions";
			$aiReq = array(
				"frequency_penalty" => 1,
				"max_tokens" => 1000,
				"messages" => array(array(
					"content" => $endMsg->text->content,
					"raw" => false,
					"role" => "user"
				)),
				//"model" => "rwkv",
				"presence_penalty" => 0,
				"presystem" => true,
				"stream" => false,
				"temperature" => 1,
				"top_p" => 0.3
			);**/
			//向AI请求消息,http
			/**$url1 = "http://region-101.seetacloud.com:26165/chat/chat";
			$aiReq = array(
				"query" => $endMsg->text->content,
				"conversation_id" => "",
  				"history_len" => -1,
				"history" => array(),
				"stream" => false,
				"model_name" => "Qwen-7B-Chat",
				"temperature" => 0.7,
				"max_tokens" => 0,
				"prompt_name" => "default"
			);**/
			//向AI请求消息,ws模式
			$url1 = "https://8919j8p607.vicp.fun/run/predict";
			$aistr = $endMsg->text->content;
			
			$aiReq = array(
				"fn_index" => 0,
				"data" => array($endMsg->text->content),
				"event_data" => null,
  				"session_hash" => "d0q5lx7q32r"
			);

			//$worker = new Worker('wss://8919j8p607.vicp.fun/queue/join');
			//https://8919j8p607.vicp.fun/run/predict

			$response = $httpPost($url1, $aiReq);
			//$response = str_replace("data: ","",$response);
			//echo "\n----------------ai返回 start-----------------\n";
			//echo "$response\n";
			//echo "----------------ai返回 end-----------------\n";
			$rspArr = json_decode($response);
			//return;
			//var_dump($rspArr);

			//发送消息
			$url1 = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?&access_token=$accessToken";
			//$url1 = $url1."&access_token=$accessToken";
			//$url1 = $url1."&touser=wmKvs_XwAAN9LcfsxiLYKjAPA-ijf-4Q";
			//$url1 = $url1."&open_kfid=$OpenKfId";
			//$url1 = $url1."&token=$token";
			//$url1 = $url1."&msgtype=text";
			//$url1 = $url1."&text=3456";
			//$url1 = $url1."&debug=1";
			//echo $url1;
			$content = "您好，当前客服不在家。";
			if($rspArr){
				//$content = $rspArr->choices[0]->message->content;
				//$content = $rspArr->text;
				$content = $rspArr->data[0];
				$content = preg_replace("/[a-zA-Z]/","",$content);
			}
			
			$post_data = array(
				"open_kfid" => $OpenKfId,
				"token" => $Token,
				"touser" => $endMsg->external_userid,
				"msgtype" => "text",
				//"text" => "3223121121",
				"text" => array(
					"content" => $content,
				),
			);
			//echo "\n龙游:".$content;
			//echo "\n龙游:$content";
			$response = $httpPost($url1, $post_data);
			//echo "\n-------------------end-------------------\n";
			//var_dump($response);

			/**
			//小程序链接，测试
			$post_data = array(
				"open_kfid" => $OpenKfId,
				"token" => $Token,
				"touser" => $endMsg->external_userid,
				"msgtype" => "msgmenu",
				//"text" => "3223121121",
				"msgmenu" => array(
					"head_content" => "您对本次服务是否满意呢? ", 
					"list" => array(
						array(
							"type" => "miniprogram",
							"miniprogram" => array(
								"appid" => "wx7ded79440863a72d",
								"pagepath" => "pages/index/index.html?userid=zhangsan&amp;orderid=123123123",
								"content" => "点击打开小程序"
							)
						),
						array(
							"type" => "view", 
							"view" => array(
								"url" => "https://work.weixin.qq.com", 
								"content" => "点击跳转到自助查询页面"
							)
						)
					),
					"tail_content" => "欢迎再次光临"
				)
			);
			//echo "\n龙游:".$content;
			//echo "\n龙游:$content";
			$response = $httpPost($url1, $post_data);
			echo $response; **/
			
		} else {
			print("ERR: " . $errCode . "\n\n");
			//exit(-1);
		}
	}

	/**回调配置时候的验证
	$get = $request->get();
	$msg_signature = $request->get('msg_signature');
	$timestamp = $request->get('timestamp');
	$nonce = $request->get('nonce');
	$echostr = $request->get('echostr');

	// 假设企业号在公众平台上设置的参数如下
	$encodingAesKey = "zndOCwNj2RsP5eZWIrjVzyJVMdknNvacUNR82F1Xb70";
	$token = "lHwn170U";
	$receiveid = "ww5be4fc8e2add2759";
	$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $receiveid);

	// get the paramters
	$sVerifyMsgSig = $request->get('msg_signature');
	$sVerifyTimeStamp = $request->get('timestamp');
	$sVerifyNonce = $request->get('nonce');
	$sVerifyEchoStr = $request->get('echostr');

	$sEchoStr = "";

	// call verify function
	$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
	if ($errCode == 0) {
		echo $sEchoStr . "\n";
	} else {
		print("ERR: " . $errCode . "\n\n");
	}
	$connection->send($sEchoStr); */
	//echo "\n---------------->进入了一位英雄!\n";
};


/**
 * aes 解密
 * @param $str
 * @param string $key
 * @param string $iv
 * @return mixed
 */
function aes_decrypt($str, $key = '', $iv = '')
{
	/**if (empty($key)) {
		$key = config('aes_key');
	}
	if (empty($iv)) {
		$iv = config('aes_iv');
	}*/
	$str = str_replace(array('-', '_'), array('+', '/'), $str);
	return json_decode(base64_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($str), MCRYPT_MODE_CBC, $iv)), true);
}

// 运行worker
Worker::runAll();
?>
